﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Yu.Cms.Common;
using Yu.Cms.IDAL;

namespace Yu.Cms.SQLServerDAL
{
    public class Tags : ITags
    {
        private readonly string TableName = "Y_Tags";

        #region ISmallType 成员


        /// <summary>
        /// 是否存在Tag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        private bool isExistTag(string tag)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from  " + TableName);
            strSql.Append(" where tag=@tag ");
            SqlParameter[] parameters = {
					new SqlParameter("@tag", SqlDbType.NVarChar,100)
                                        };
            parameters[0].Value = tag;
            return DbHelperMsSQL.Exists(strSql.ToString(), parameters);
        }

      

        /// <summary>
        /// 添加文章Tag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public int AddTag(Model.Tags model)
        {
            if (isExistTag(model.tag)) //存在tag
            {
                return this.Update(model) ;
            }
            else  //不存在
            {
               return this.Add(model);
            }
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private int Add(Model.Tags model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into "+ TableName +"(");
            strSql.Append("tag,tnum,taids)");
            strSql.Append(" values (");
            strSql.Append("@tag,@tnum,@taids)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@tag", SqlDbType.NVarChar,100),
					new SqlParameter("@tnum", SqlDbType.Int,4),
					new SqlParameter("@taids", SqlDbType.NVarChar,100)};
            parameters[0].Value = model.tag;
            parameters[1].Value = 1;
            parameters[2].Value = model.taids;

            object obj = DbHelperMsSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return -1;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }


        public int Update(Model.Tags model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update "+ TableName +" set ");          
            strSql.Append("tnum=@tnum,");
            strSql.Append("taids=@taids");
            strSql.Append(" where tagid=@tagid");
            SqlParameter[] parameters = {				
					new SqlParameter("@tnum", SqlDbType.Int,4),
					new SqlParameter("@taids", SqlDbType.NVarChar,100),
					new SqlParameter("@tagid", SqlDbType.Int,4)};
          
            parameters[1].Value = model.tnum;
            parameters[2].Value = model.taids;
            parameters[3].Value = model.tagid;

            return DbHelperMsSQL.ExecuteSql(strSql.ToString(), parameters);
             
        }

        public int Delete(int tagid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from Y_Tags ");
            strSql.Append(" where tagid=@tagid");
            SqlParameter[] parameters = {
					    new SqlParameter("@tagid", SqlDbType.Int,4)
                     };
            parameters[0].Value = tagid;

           return DbHelperMsSQL.ExecuteSql(strSql.ToString(), parameters);
            
        }

        public int DeleteList(string tagidlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from "+ TableName);
            strSql.Append(" where tagid in (" + tagidlist + ")  ");
            return DbHelperMsSQL.ExecuteSql(strSql.ToString());
        }

        /// <summary>
        /// 根据tagid返回 tag 实体类 单笔资料 (Y_tag)
        /// </summary>
        /// <param name="tagid"></param>
        /// <returns></returns>
        public Model.Tags GetModel(int tagid)
        {
            QueryParam qp = new QueryParam();
            qp.Where = " Where tagid=" + tagid;
            Yu.Cms.Model.Tags fam = new Yu.Cms.Model.Tags();
            int RecordCount;
            IList<Yu.Cms.Model.Tags> lst = this.GetList(qp, out RecordCount);
            if (lst.Count > 0)
            {
                fam = lst[0];
            }
            return fam;
        }

      

        /// <summary>
        /// 返回所有TagList
        /// </summary>
        /// <returns></returns>
        public IList<Model.Tags> GetTagList()
        {
            QueryParam qp = new QueryParam();
            int CurrentPageIndex = 1;
            int PageSize = int.MaxValue;
            int RecordCount;
            qp.PageIndex = CurrentPageIndex;
            qp.PageSize = PageSize;
            return this.GetList(qp, out RecordCount);
        }
        #endregion

        /// <summary>
        /// 将记录集转为Y_TagsEntity实体类 (Y_SmallType)
        /// </summary>
        /// <param name="dr">记录集</param>
        /// <param name="Fileds">字段名列表</param>
        /// <returns>Y_TagsEntity</returns>
        protected Yu.Cms.Model.Tags Populate_Tags(IDataReader dr, Dictionary<string, string> Fileds)
        {
            Yu.Cms.Model.Tags nc = new Yu.Cms.Model.Tags();

            if (Fileds.ContainsKey("tagid") && !Convert.IsDBNull(dr["tagid"])) nc.tagid = Convert.ToInt32(dr["tagid"]); // 自动ID
            if (Fileds.ContainsKey("tag") && !Convert.IsDBNull(dr["tag"])) nc.tag = Convert.ToString(dr["tag"]).Trim(); // Tag名称
            if (Fileds.ContainsKey("tnum") && !Convert.IsDBNull(dr["tnum"])) nc.tnum = Convert.ToInt32(dr["tnum"]); // 数量
            if (Fileds.ContainsKey("taids") && !Convert.IsDBNull(dr["taids"])) nc.taids = Convert.ToString(dr["taids"]).Trim(); // id数量
            return nc;
        }


        /// <summary>
        /// 返回Y_Tags实体类的IList对象 (Y_Content)
        /// </summary>
        /// <param name="qp">查询类(非安全函数,传入参数请进行Sql字符串过滤)</param>
        /// <param name="RecordCount">返回记录总数</param>
        /// <returns>Y_Tags实体类的IList对象(Y_Content)</returns>
        public IList<Yu.Cms.Model.Tags> GetList(QueryParam qp, out int RecordCount)
        {
            qp.TableName = TableName;
            if (qp.Orderfld == null)
            {
                qp.Orderfld = "tagid";
            }
            else if (qp.Orderfld != "tagid")
            {
                qp.Orderfld += ",tagid";
            }

            if (qp.ReturnFields == null)
            {
                qp.ReturnFields = "*";
            }
            else
            {
                qp.ReturnFields += ",";
                qp.ReturnFields += qp.Orderfld;
            }
            DbHelperMsSQL.PopulateDelegate<Yu.Cms.Model.Tags> mypd = new DbHelperMsSQL.PopulateDelegate<Yu.Cms.Model.Tags>(this.Populate_Tags);
            return DbHelperMsSQL.GetRecordListBySql(mypd, qp, out RecordCount);
        }
    }
}
